package com.example.tliasfight.service.impl;

import com.example.tliasfight.anno.Mylog;
import com.example.tliasfight.mapper.DeptMapper;
import com.example.tliasfight.mapper.EmpMapper;
import com.example.tliasfight.pojo.Dept;
import com.example.tliasfight.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService
{
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private LogServiceImpl deptLogService;
//    @Autowired
//    private TransactionTemplate template;
     @Override
    public List<Dept> selectAll()
    {
        return deptMapper.selectAll();
    }
    @Transactional(rollbackFor = Exception.class)
    @Override

    public void deleteById (Integer id) throws Exception {
        try {
            deptMapper.deleteById(id);
         //    int i=1/0;//测试.这是一个运行时的异常RuntimeException,默认的rollbackFor属性可以回滚事务，但是如果不是RuntimeException，不会回滚事务
            // if(true){throw new Exception();}

            empMapper.deleteByDeptId(id);//同时也要删除被删除部门下的所有的员工


        } finally {

      //     TransactionTemplate template=new TransactionTemplate();
//            String describe="删除了部门"+id;
//            DeptLog deptLog=new DeptLog(LocalDateTime.now(),describe);
//
//            template.execute(status ->
//            {    //记录部门表的操作日志，不管操作的成功与失败
//                deptLogService.insert(deptLog);
//                return null;
//            });
        }
    }

    @Override

    public void addDept(Dept dept)
    {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.addDept(dept);
    }
    @Override
    public Dept selectById(Integer id)
    {
      return deptMapper.selectById(id);
    }
    @Override

    public void updateDeptNameById(Dept dept)
    {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateDeptNameById(dept);
    }
}
